#!/usr/bin/env python

import gtk
class Run:
    
 
    
    def RunProgram(self, code, tape, codeNumberOfLines, numberOfElementsOnTape, startPosition):
        
        
        resultTape=range(numberOfElementsOnTape)
        for i in range(0, numberOfElementsOnTape):
            resultTape[i] = tape[0][i]
            
            
         
        StopCounter= 0
        tapePosition = startPosition-1
        nameOfNextState = ""
        counter = 0
        Line = 0
        STATUS = 1
        
        while STATUS == 1: 
         
            if StopCounter >= 5000:     #in case of infinite loop
                STATUS = 0
                return resultTape,1, "Stopped because of too many runs \"" +str(StopCounter) +"\""
                
                
            StopCounter+=1 
                
 
        
            resultTape[tapePosition] = code[Line][3]
            
            if code[Line][4] == "L":
                tapePosition-=1
                if tapePosition < 0:
                    return resultTape, 1, "ERROR on line " +str(Line+1) +": \nTape out of bounds: \"" +str(tapePosition) +"\""
            elif code[Line][4] == "R":
                tapePosition+=1
                if tapePosition > (numberOfElementsOnTape-1):
                    return resultTape, 1, "ERROR on line " +str(Line+1) +": \nTape out of bounds: \"" +str(tapePosition) +"\""
            elif code[Line][4] == "-":
                tapePosition = tapePosition
            else:
                return resultTape, 1, "ERROR on line " +str(Line+1) +": \nNo such direction: \"" +code[Line][4] +"\""
                
                break
        
            nameOfNextState = code[Line][5]
            status = "State: \""+nameOfNextState+"\" not found"
            
            for counter in range(0, codeNumberOfLines):
                if code[counter][1] == nameOfNextState:
                    status = "state found"
                    if code[counter][2] == resultTape[tapePosition]:
                        #print "usable state found on line: ", counter
                        status = "usable state found"
                        Line = counter
                        break
             
            if nameOfNextState == "HALT":
                break
                
            if status == "State: \""+nameOfNextState+"\" not found":
                return resultTape,1,status                
        #return "Succes"
        return resultTape, 0, "Program done"

 
